<template>
  <el-breadcrumb class="app-bread-crumb" :separator="separator">
    <transition-group name="list">
      <el-breadcrumb-item v-for="(item, index) in leveList" :key="item.path">
        <!-- 最后一个不可点击 -->
        <span v-if="item.redirect === 'noRedirect' || index === leveList.length -1" class="no-redirect">
          {{ item.meta.title }}
        </span>
        <a v-else @click.prevent="handleClick(item)">
          {{ item.meta.title }}
        </a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import pathToRegExp from 'path-to-regexp'
export default {
  name: 'Breadcrumb',
  props: {
    separator: {
      type: String,
      default: '/'
    }
  },
  data() {
    return {
      leveList: null
    }
  },
  watch: {
    $route: {
      handler(route) {
        if (route.path.startsWith('/redirect/')) {
          return
        }
        this.getBreadCrumd()
      }
    }
  },
  created() {
    this.getBreadCrumd()
  },
  methods: {
    getBreadCrumd() {
      // 获取到匹配到的路由中的所有的title
      let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
      const first = matched[0]
      // 判断第一个是否是 dashboard
      if (!this.isDashboard(first)) {
        matched = [{ path: '/dashboard', meta: { title: '首页' }}].concat(matched)
      }
      this.leveList = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumd !== false)
      console.log('leveList', this.leveList)
    },
    isDashboard(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase() || name.trim() === 'layout'
    },
    compliePath(path) {
      // https://www.npmjs.com/package/path-to-regexp
      const { params } = this.$route
      const toPath = pathToRegExp.compile(path)
      // 根据参数和路由进行拼接
      return toPath(params)
    },
    handleClick(route) {
      console.log('route', route)
      const { redirect, path } = route
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(this.compliePath(path))
    }
  }
}
</script>
<style lang="scss" scoped>
.app-bread-crumb {
  display: inline-block;
  height: 100%;
  line-height: 49px;
  font-size: 16px;
  margin-left: 10px;
}
.no-redirect {
  color: #97a8be;
  cursor: text;
}

</style>
